/*
 * measure.c
 *
 * Created: 2012-07-26 08:45:55
 *  Author: Antrykot
 */ 



#include "measure.h"

u8 adc_chan = 0;
u16 adc_readout = 0;

u16 x_aku = STD_AKU_MINUS;
u16 x_pow = STD_AKU_MINUS;

u16 v_aku;
u16 v_pow;
u16 v_dc;
u16 v_temp;



void calc_pa()
{
	adc_chan = 0;
	adc_read();
	
	float ap = adc_readout * 24 +;
	
}


void calc_aku()
{
	adc_chan = 1;
	adc_read();
	float aku = adc_readout * 6.10;
	aku += x_aku - STD_AKU_MINUS;
	v_aku = aku;
}

void calc_pow()
{
	adc_chan = 3;
	adc_read();
	float pow = adc_readout * 6.10;
	pow += x_pow - STD_AKU_MINUS;
	v_pow = pow;
}

void calc_dc()
{
	adc_chan = 2;
	adc_read();
	float dc = adc_readout * 6.10;
	v_dc = dc;
}

void adc_read()
{
	cli();
	
	DIN_HIG;
	WAITUS(20);
	CS_LOW;
	WAITUS(20);
	adc_clk();
	DIN_HIG;		// single ended
	adc_clk();
	DIN_LOW;		// D2
	adc_clk();
	if (adc_chan & 0x02)
	{
		DIN_HIG;
	}		
	else
	{
		DIN_LOW;
	}		
	adc_clk();
	if (adc_chan & 0x01)
	{
		DIN_HIG;
	}		
	else
	{
		DIN_LOW;
	}		
	adc_clk(); // D0
	DIN_HIG;
	adc_clk(); // empty
	adc_clk(); // empty
	adc_clk(); // empty
	
	adc_readout = 0;
	for (i8 c = 11; c >= 0; c--)
	{
		CLK_HIG;
		WAITUS(20);
		CLK_LOW;
		//WAITUS(5);
		adc_readout |= ( ( DOUT ) << c);
	}		
		
	CS_HIG;
	DIN_HIG;
	CLK_HIG;
	sei();
}

inline void adc_readbit(u8 offset)
{
	CLK_HIG;
	WAITUS(10);
	CLK_LOW;
	WAITUS(10);
	adc_readout |= ( ( DOUT ) << offset);
}

void adc_clk()
{
	CLK_LOW;
	WAITUS(20);
	CLK_HIG;
	WAITUS(20);
}

void ser_def_low()
{
		nxa = read_double(EEP_SNXA);
		nxb = read_double(EEP_SNXB);
		
		x_zn = read_word(EEP_X_SZN);
		x_cn = read_word(EEP_X_SCN);
				
		write_double(EEP_NXA,nxa);
		write_double(EEP_NXB,nxb);
		
		
		write_word(EEP_X_ZN,x_zn);
		write_word(EEP_X_CN,x_cn);

		stn = read_word(EEP_STN);


		
}

void ser_def_high()
{
		stw1 = read_word(EEP_STW1);
		stw2 = read_word(EEP_STW2);
		
		wxa = read_double(EEP_SWXA);
		wxb = read_double(EEP_SWXB);
		wxc = read_double(EEP_SWXC);

		write_double(EEP_WXA,wxa);
		write_double(EEP_WXB,wxb);
		write_double(EEP_WXC,wxc);
		

		x_zw = read_word(EEP_X_SZW);
		x_cw = read_word(EEP_X_SCW);
		
		write_word(EEP_X_ZW,x_zw);
		write_word(EEP_X_CW,x_cw);



}
